//
//  LSYNetUtil.m
//  LSYReader
//
//  Created by sam on 2018/3/23.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "EncodeDet.h"
#import "LSYNetUtil.h"
#import "LSYFileUtil.h"
#import "NSString+EV.h"
#import "NSDictionary+EV.h"

@implementation LSYNetUtil
+(NSString *)moreUrl:(id)data rule:(LSYParseModel *)rule relativeUrl:(NSURL *)url {
    if (![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    if ([(NSData *)data length]<=0) {
        return nil;
    }
    NSString *html = [LSYNetUtil htmlString:data];
    HTMLDocument *doc = [HTMLDocument documentWithString:html];
    NSArray *moreEls = [doc querySelectorAll:rule.searchMore];
    
    return @"";
}
+(NSArray *)books:(id)data rule:(LSYParseModel *)rule relativeUrl:(NSURL *)url {
    if (![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    if ([(NSData *)data length]<=0) {
        return nil;
    }
    NSString *html = [LSYNetUtil htmlString:data];
    HTMLDocument *doc = [HTMLDocument documentWithString:html];
    NSArray *books = [doc querySelectorAll:rule.books];
    NSMutableArray *tmpBooks = [NSMutableArray array];
    for (HTMLElement *el in books) {
        [tmpBooks addObject:[LSYBook book:el rule:rule relativeUrl:url]];
    }
    return tmpBooks;
}

+(NSString*)chapterContent:(id)data rule:(LSYParseModel *)rule {
    if (![data isKindOfClass:[NSData class]]) {
        return @"解析失败...";
    }
    if ([(NSData *)data length]<=0) {
        return @"解析失败...";
    }
    NSString *html = [LSYNetUtil htmlString:data];
    HTMLDocument *doc = [HTMLDocument documentWithString:html];
    
    NSString *content = [rule getElText:doc.rootElement rule:rule.content relativeUrl:nil isHtml:YES];
    doc = [HTMLDocument documentWithString:content];
    
    //content remve
    NSArray *removes = rule.contentRemoves;
    for (NSString *remove in removes) {
        NSArray *elements = [doc querySelectorAll:remove];
        for (HTMLElement *el in elements) {
            [el removeFromParentNode];
        }
    }
    content = doc.rootElement.innerHTML;
    //reg remove some extra text
    NSArray *replaces = rule.contentReplaces;
    for (NSDictionary *dict in replaces) {
        BOOL enabled = [dict ev_boolForKey:@"enabled"];
        if (enabled) {
            BOOL noRegular = [dict ev_boolForKey:@"noRegular"];
            NSString *regExpString = [dict ev_stringObjectForKey:@"first"];
            NSString *template = [dict ev_stringObjectForKey:@"second"];
            if (!noRegular) {
                content = [content stringByReplacingOccurrencesOfString:regExpString
                                                                      withString:template
                                                                         options:NSRegularExpressionSearch
                                                                           range:NSMakeRange (0, content.length)];
            } else {
                content = [content stringByReplacingOccurrencesOfString:regExpString withString:template];
            }
        }
    }
    return content?:@"解析失败...";
}

+(NSArray *)chapters:(id)data book:(LSYBook *)book relativeUrl:(NSURL *)url {
    if (![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    if ([(NSData *)data length]<=0) {
        return nil;
    }
    NSString *html = [LSYNetUtil htmlString:data];
    HTMLDocument *doc = [HTMLDocument documentWithString:html];
    NSArray *chapters = [doc querySelectorAll:book.rule.chapters];
    NSMutableArray *tmpChapters = [NSMutableArray array];
    NSMutableDictionary *keyChapters = [NSMutableDictionary dictionary];
    NSInteger index =0;
    for (HTMLElement *el in chapters) {
        LSYChapter *chapter = [LSYChapter chapter:el book:book relativeUrl:url];
        NSArray *chapters = [keyChapters ev_arrayObjectForKey:chapter.chapterUrl];
        NSMutableArray *mutableChapters = [NSMutableArray arrayWithArray:chapters];
        [mutableChapters addObject:chapter];
        [keyChapters setObject:mutableChapters forKey:chapter.chapterUrl];
        [tmpChapters addObject:chapter];
        index ++;
    }
    NSMutableArray *delChapters = [NSMutableArray array];
    [keyChapters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSMutableArray *chapters = [NSMutableArray arrayWithArray:obj];
        [chapters removeLastObject];
        [delChapters addObjectsFromArray:chapters];
    }];
    [tmpChapters removeObjectsInArray:delChapters];
    return tmpChapters;
}

+(NSString *)chapterDetail:(id)data book:(LSYBook *)book relativeUrl:(NSURL *)url {
    if (![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    if ([(NSData *)data length]<=0) {
        return nil;
    }
    NSString *html = [LSYNetUtil htmlString:data];
    HTMLDocument *doc = [HTMLDocument documentWithString:html];
    NSString *detailUrl = [book.rule getElText:doc rule:book.rule.detailChaptersUrl relativeUrl:url];
    if(book.bookIcon.length<=0) {
        book.bookIcon = [book.rule getElText:doc.rootElement rule:book.rule.detailBookIcon relativeUrl:url];
    }
    if (detailUrl.length>0) {
        return detailUrl;
    }
    return nil;
}

+(NSString *)htmlString:(NSData *)data {
    CFStringEncoding cfEncode = 0;
    const char *encode = get_encoding(data.bytes, (unsigned int)data.length);
    if (encode == NULL) {
        cfEncode = kCFStringEncodingUTF8;
    } else {
        NSString* encodeStr=[[NSString alloc] initWithCString:encode encoding:NSUTF8StringEncoding];
        if([encodeStr isEqualToString:@"gb18030"]) {
            cfEncode=kCFStringEncodingGB_18030_2000;
        }else if([encodeStr isEqualToString:@"Big5"]){
            cfEncode= kCFStringEncodingBig5;
        }else if([encodeStr isEqualToString:@"UTF-8"]){
            cfEncode= kCFStringEncodingUTF8;
        }else if([encodeStr isEqualToString:@"Shift_JIS"]){
            cfEncode= kCFStringEncodingShiftJIS;
        }else if([encodeStr isEqualToString:@"windows-1252"]){
            cfEncode= kCFStringEncodingWindowsLatin1;
        }else if([encodeStr isEqualToString:@"x-euc-tw"]){
            cfEncode= kCFStringEncodingEUC_TW;
        }else if([encodeStr isEqualToString:@"EUC-KR"]){
            cfEncode= kCFStringEncodingEUC_KR;
        }else if([encodeStr isEqualToString:@"EUC-JP"]){
            cfEncode=kCFStringEncodingEUC_JP;
        }
    }
    NSString *str=[[NSString alloc] initWithData:data encoding:CFStringConvertEncodingToNSStringEncoding(cfEncode)];
    return str;
}

+(NSString *)ownerText:(HTMLNode *)node {
    NSString *htmlStr = node.innerHTML;
    NSRange location  = [htmlStr rangeOfString:@"<"];
    if (location.location != NSNotFound) {
        return [htmlStr substringToIndex:location.length].ev_trim;
    }
    return node.textContent.ev_trim;
}

// cache check
+(BOOL)cachedChapter:(LSYChapter *)chapter {
    NSString *path = [LSYFileUtil absChapterPath:chapter];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return YES;
    } else {
        return NO;
    }
}
+(NSString *)cacheChapterContent:(LSYChapter *)chapter {
    NSString *path = [LSYFileUtil absChapterPath:chapter];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *err;
        NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
        if (err) {
            return @"";
        }
        return content;
    } else {
        return @"";
    }
}

// save cache
+ (void)saveCahpterContent:(NSString *)content chapter:(LSYChapter *)chapter {
    NSString *path  = [LSYFileUtil absChapterPath:chapter];
    if (content.length>0) {
        [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

@end
